package com.edgar;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.List;

public class RemoveExpireFileZoneTask implements Runnable {

    private static final Logger LOG = LoggerFactory.getLogger(RemoveExpireFileZoneTask.class);

    @Override
    public void run() {
        final List<FileZone> fileZoneList = FileZone.dao.findAll();
        LOG.info("File zone list {}", fileZoneList);

        Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                for (FileZone fileZone : fileZoneList) {

                    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
                    DateTime deleteDateTime = DateTime.parse(fileZone.getStr(FileZone.DELETE_TIME), dateTimeFormatter);
                    int betweenDay = Days.daysBetween(deleteDateTime, DateTime.now()).getDays();
                    LOG.info("Days between {}", betweenDay);
                    if (betweenDay < AppConfig.p.getInt("file.zone.data.retain.days"))
                        continue;

                    LOG.info("Remove file zone {}" + fileZone);

                    boolean isFileZoneDelete = FileZone.dao.deleteById(fileZone.getStr(FileZone.ZONE_ID));
                    if (!isFileZoneDelete) return false;

                    boolean isFileBoxDelete = FileBox.dao.deleteByZoneId(fileZone.getStr(FileZone.ZONE_ID));
                    if (!isFileBoxDelete) return false;

                }
                return true;
            }
        });

    }
}
